<template>
  <div class="form-widget-container">
    <el-form
      class="full-height-width widget-form"
      :size="size"
      :label-position="labelPosition"
      :class="[customClass, layoutType + '-layout']"
      :validate-on-rule-change="false"
    >
      <template v-if="designer.widgetList.length === 0">
        <div class="no-widget-hint">{{ i18nt('designer.noWidgetHint') }}</div>
      </template>

      <div class="form-widget-list" :style="{ 'min-height': `${minHeight}px` }">
        <draggable
          :="dragAttrs"
          :list="designer.widgetList"
          :move="checkMove"
          @end="onDragEnd"
          @add="onDragAdd"
          @update="onDragUpdate"
        >
          <template #item="{ element: widget, index }">
            <div class="transition-group-el">
              <template v-if="'container' === widget.category">
                <component
                  :is="getWidgetName(widget)"
                  :key="widget.id"
                  :widget="widget"
                  :designer="designer"
                  :parent-list="designer.widgetList"
                  :parent-widget="null"
                  :index-of-parent-list="index"
                  :minHeight="minHeight"
                >
                </component>
              </template>
              <template v-else>
                <component
                  :is="getWidgetName(widget)"
                  :key="widget.id"
                  :field="widget"
                  :designer="designer"
                  :parent-list="designer.widgetList"
                  :design-state="true"
                  :parent-widget="null"
                  :index-of-parent-list="index"
                >
                </component>
              </template>
            </div>
          </template>
        </draggable>
      </div>
    </el-form>
  </div>
</template>

<script>
import '@/components/form-designer/form-widget/container-widget/index';
import i18n from '@/utils/i18n';
import XEUtils from 'xe-utils';
import { VfMessage } from '@/utils/vf-utils'
import FieldComponents from '@/components/form-designer/form-widget/field-widget/index';

export default {
  name: 'VFormWidget',
  componentName: 'VFormWidget',
  mixins: [i18n],
  components: {
    ...FieldComponents,
  },
  props: {
    designer: Object,
    formConfig: Object,
    optionData: {
      //prop传入的选项数据
      type: Object,
      default: () => ({}),
    },
    globalDsv: { type: Object, default: () => ({}) },
    minHeight: { type: Number },
  },
  provide() {
    return {
      formRef: this,
      // ref列表数据
      refList: this.widgetRefList,
      // 解决provide传递formConfig属性的响应式更新问题！！
      getFormConfig: () => this.formConfig,
      // 全局数据源变量
      getGlobalDsv: () => this.globalDsv,
      // 获取选项数据
      getOptionData: () => this.optionData,
      // 全局对象
      globalModel: { formModel: this.formModel },
      // 全局的选项数据
      globalOptionData: this.optionData,
    };
  },
  inject: ['getDesignerConfig'],
  data() {
    return {
      formModel: {},
      widgetRefList: {},
      // 拖拽组件属性
      dragAttrs: {
        tag: 'transition-group',
        group: 'dragGroup',
        handle: '.drag-handler',
        itemKey: 'id',
        animation: 300,
        ghostClass: 'ghost',
        componentData: { name: 'fade' }
      },
    };
  },
  computed: {
    labelPosition() {
      if (!!this.designer.formConfig && !!this.designer.formConfig.labelPosition) {
        return this.designer.formConfig.labelPosition;
      }

      return 'left';
    },

    size() {
      if (!!this.designer.formConfig && !!this.designer.formConfig.size) {
        return this.designer.formConfig.size;
      }

      return 'default';
    },

    customClass() {
      return this.designer.formConfig.customClass || '';
    },

    layoutType() {
      return this.designer.getLayoutType();
    },
  },
  watch: {
    // 'designer.widgetList': {
    //   deep: true,
    //   handler(val) {
    //     //
    //   },
    // },

    // 'designer.formConfig': {
    //   deep: true,
    //   handler(val) {
    //     //
    //   },
    // },
  },
  created() {
    this.designer.initDesigner(!!this.getDesignerConfig().resetFormJson);
    this.designer.loadPresetCssCode(this.getDesignerConfig().presetCssCode);
  },
  mounted() {
    this.disableFirefoxDefaultDrop(); /* 禁用Firefox默认拖拽搜索功能!! */
    this.designer.registerFormWidget(this);
  },
  methods: {
    getWidgetName(widget) {
      return widget.type + '-widget';
    },

    disableFirefoxDefaultDrop() {
      let isFirefox = navigator.userAgent.toLowerCase().indexOf('firefox') !== -1;
      if (isFirefox) {
        document.body.ondrop = function (event) {
          event.stopPropagation();
          event.preventDefault();
        };
      }
    },

    onDragEnd(evt) {
      //console.log('drag end000', evt)
    },

    onDragAdd(evt) {
      // console.log('onDragAdd', evt)
      const newIndex = evt.newIndex;
      if (!!this.designer.widgetList[newIndex]) {
        this.designer.setSelected(this.designer.widgetList[newIndex]);
      }
      console.log('onDragAdd')
      this.designer.emitHistoryChange();
    },

    onDragUpdate() {
      /* 在VueDraggable内拖拽组件发生位置变化时会触发update，未发生组件位置变化不会触发！！ */
      console.log('onDragUpdate')
      this.designer.emitHistoryChange();
    },

    checkMove(evt) {
      return this.designer.checkWidgetMove(evt);
    },

    getFormData() {
      return this.formModel;
    },

    getWidgetRef(widgetName, showError = false) {
      let foundRef = this.widgetRefList[widgetName];
      if (!foundRef && !!showError) {
        VfMessage.error(this.i18nt('designer.hint.refNotFound') + widgetName);
      }
      return foundRef;
    },
    getWidgetRefs(widgetName, showError = false) {
      const widgetPools = this.widgetRefList;
      const foundRefs = [];
      const foundRefsKey = [];
      XEUtils.objectEach(widgetPools, (item, key) => {
        if (key.startsWith(widgetName)) {
          foundRefs.push(item);
          foundRefsKey.push(key);
        }
      });
      return {
        count: foundRefs.length || 0,
        foundRef: widgetPools[widgetName],
        foundRefs: foundRefs,
        foundRefsKey: foundRefsKey,
      };
    },

    getSelectedWidgetRef() {
      let wName = this.designer.selectedWidgetName;
      return this.getWidgetRef(wName);
    },

    clearWidgetRefList() {
      Object.keys(this.widgetRefList).forEach(key => {
        delete this.widgetRefList[key];
      });
    },

    deleteWidgetRef(widgetRefName) {
      delete this.widgetRefList[widgetRefName];
    },
  },
};
</script>

<style lang="scss" scoped>
.container-scroll-bar {
  :deep(.el-scrollbar__wrap),
  :deep(.el-scrollbar__view) {
    overflow-x: hidden;
  }
}

.form-widget-container {
  padding: 10px;
  background: #f1f2f3;
  overflow-x: hidden;
  overflow-y: auto;

  .el-form.full-height-width {
    height: 100%;
    padding: 6px;
    background: #ffffff;
    .no-widget-hint {
      position: absolute;
      left: 0;
      right: 0;
      top: 0;
      bottom: 0;
      height: 100%;
      display: flex;
      align-items: center;
      justify-content: center;
      text-align: center;
      font-size: 18px;
      color: #999999;
    }

    .form-widget-list {
      // min-height: calc(100vh - 56px - 68px);
      // min-height: calc(100vh - 40px - 20px - 6px - 6px);
      // padding: 3px;
      position: relative;
    }
  }

  // .el-form.PC-layout {
  //   //
  // }

  .el-form.Pad-layout {
    margin: 0 auto;
    max-width: 960px;
    border-radius: 15px;
    box-shadow: 0 0 1px 10px #495060;
  }

  .el-form.H5-layout {
    margin: 0 auto;
    width: 420px;
    border-radius: 15px;
    //border-width: 10px;
    box-shadow: 0 0 1px 10px #495060;
  }

  .el-form.widget-form :deep(.el-row) {
    padding: 8px;
    margin-bottom: 12px;
  }
}

.grid-cell {
  min-height: 30px;
  border-right: 1px dotted #cccccc;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.5s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}
</style>
